from PyQt5.QtWidgets import QWidget, QLabel, QGridLayout, QApplication, \
    QStackedWidget, QPushButton, QHBoxLayout, QVBoxLayout, QScrollArea, \
    QLineEdit, QFileDialog, QGraphicsDropShadowEffect, QDateTimeEdit, \
    QPlainTextEdit
from PyQt5.QtGui import QPixmap, QFont, QIntValidator, QDoubleValidator, QCursor
from PyQt5.QtCore import Qt, pyqtSignal, QDate
from Dialog import FileDialog, WarningMessageBox
from base64 import b64encode, b64decode
import requests
import sys
import copy
from shopInterfaceTools import shopItem, slideButton, picEditableLabel
import cv2
import numpy as np
from handler.activityHandle import activityHandle
import time
import shutil
import os

activityList = [{
        "activity_id": 1,
        "activity_title": "全民种动园",  # 标题
        "activity_count": 50,  # 预设参加人数
        "status": 0,  # 状态
        "imagesSlider": [
            "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3205314663,2167162864&fm=26&gp=0.jpg",
            "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3992045535,69144840&fm=26&gp=0.jpg",
            "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3156874013,635811390&fm=26&gp=0.jpg"
        ],   # 轮播图
        "defaultImgIndex": 0,  # 默认图片索引（取轮播图）
        "activity_signed": 12,  # 已参加人数
        "price": 59,  # 价格
        "activity_unit": "元/人",  # 单位
        "activity_start_date": "2020-07-20",  # 活动开始时间
        "activity_end_date": "2020-08-20",  # 活动结束时间
        "sign_start_date": "2020-07-13",  # 报名开始时间
        "sign_end_date": "2020-07-28",  # 报名结束时间
        "service_tel":"0721-8392580",   # 咨询电话
        "address": "测试",  # 地址
        "activity_content": "虽然做了一件好事，但很有可能因此招来他人的无端猜测，例如被质疑是否藏有其他利己动机等，乃至谴责。即便如此，还是要做好事。",#介绍
        "imageContent":[
            "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1887942828,972848009&fm=26&gp=0.jpg",
            "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1956320807,1368482897&fm=26&gp=0.jpg",
            "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2192842524,640789728&fm=26&gp=0.jpg",
            "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2167237248,612060343&fm=26&gp=0.jpg",
            "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1925142767,3806138753&fm=26&gp=0.jpg",
        ],  # 图片详情
    },
{
        "activity_id": "1",
        "activity_title": "全民种动园",  # 标题
        "activity_count": 50,  # 预设参加人数
        "status": 0,  # 状态
        "imagesSlider": [
            "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3205314663,2167162864&fm=26&gp=0.jpg",
            "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3992045535,69144840&fm=26&gp=0.jpg",
            "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3156874013,635811390&fm=26&gp=0.jpg"
        ],   # 轮播图
        "defaultImgIndex": 1,  # 默认图片索引（取轮播图）
        "activity_signed": 12,  # 已参加人数
        "price": 59,  # 价格
        "activity_unit": "元/人",  # 单位
        "activity_start_date": "2020-07-20",  # 活动开始时间
        "activity_end_date": "2020-08-20",  # 活动结束时间
        "sign_start_date": "2020-07-13",  # 报名开始时间
        "sign_end_date": "2020-07-28",  # 报名结束时间
        "service_tel":"0721-8392580",   # 咨询电话
        "address": "测试",  # 地址
        "activity_content": "虽然做了一件好事，但很有可能因此招来他人的无端猜测，例如被质疑是否藏有其他利己动机等，乃至谴责。即便如此，还是要做好事。",#介绍
        "imageContent":[
            "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1887942828,972848009&fm=26&gp=0.jpg",
            "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1956320807,1368482897&fm=26&gp=0.jpg",
            "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2192842524,640789728&fm=26&gp=0.jpg",
            "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2167237248,612060343&fm=26&gp=0.jpg",
            "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1925142767,3806138753&fm=26&gp=0.jpg",
        ],  # 图片详情
    },
{
        "activity_id": "1",
        "activity_title": "全民种动园",  # 标题
        "activity_count": 50,  # 预设参加人数
        "status": 0,  # 状态
        "imagesSlider": [
            "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3205314663,2167162864&fm=26&gp=0.jpg",
            "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3992045535,69144840&fm=26&gp=0.jpg",
            "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3156874013,635811390&fm=26&gp=0.jpg"
        ],   # 轮播图
        "defaultImgIndex": 2,  # 默认图片索引（取轮播图）
        "activity_signed": 12,  # 已参加人数
        "price": 59,  # 价格
        "activity_unit": "元/人",  # 单位
        "activity_start_date": "2020-07-20",  # 活动开始时间
        "activity_end_date": "2020-08-20",  # 活动结束时间
        "sign_start_date": "2020-07-13",  # 报名开始时间
        "sign_end_date": "2020-07-28",  # 报名结束时间
        "service_tel":"0721-8392580",   # 咨询电话
        "address": "测试",  # 地址
        "activity_content": "虽然做了一件好事，但很有可能因此招来他人的无端猜测，例如被质疑是否藏有其他利己动机等，乃至谴责。即便如此，还是要做好事。",#介绍
        "imageContent":[
            "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1887942828,972848009&fm=26&gp=0.jpg",
            "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1956320807,1368482897&fm=26&gp=0.jpg",
            "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2192842524,640789728&fm=26&gp=0.jpg",
            "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2167237248,612060343&fm=26&gp=0.jpg",
            "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1925142767,3806138753&fm=26&gp=0.jpg",
        ],  # 图片详情
    },
{
        "activity_id": "1",
        "activity_title": "全民种动园",  # 标题
        "activity_count": 50,  # 预设参加人数
        "status": 0,  # 状态
        "imagesSlider": [
            "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3205314663,2167162864&fm=26&gp=0.jpg",
            "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3992045535,69144840&fm=26&gp=0.jpg",
            "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3156874013,635811390&fm=26&gp=0.jpg"
        ],   # 轮播图
        "defaultImgIndex": 0,  # 默认图片索引（取轮播图）
        "activity_signed": 12,  # 已参加人数
        "price": 59,  # 价格
        "activity_unit": "元/人",  # 单位
        "activity_start_date": "2020-07-20",  # 活动开始时间
        "activity_end_date": "2020-08-20",  # 活动结束时间
        "sign_start_date": "2020-07-13",  # 报名开始时间
        "sign_end_date": "2020-07-28",  # 报名结束时间
        "service_tel":"0721-8392580",   # 咨询电话
        "address": "测试",  # 地址
        "activity_content": "虽然做了一件好事，但很有可能因此招来他人的无端猜测，例如被质疑是否藏有其他利己动机等，乃至谴责。即便如此，还是要做好事。",#介绍
        "imageContent":[
            "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1887942828,972848009&fm=26&gp=0.jpg",
            "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1956320807,1368482897&fm=26&gp=0.jpg",
            "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2192842524,640789728&fm=26&gp=0.jpg",
            "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2167237248,612060343&fm=26&gp=0.jpg",
            "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1925142767,3806138753&fm=26&gp=0.jpg",
        ],  # 图片详情
    },
{
        "activity_id": "1",
        "activity_title": "全民种动园",  # 标题
        "activity_count": 50,  # 预设参加人数
        "status": 0,  # 状态
        "imagesSlider": [
            "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3205314663,2167162864&fm=26&gp=0.jpg",
            "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3992045535,69144840&fm=26&gp=0.jpg",
            "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3156874013,635811390&fm=26&gp=0.jpg"
        ],   # 轮播图
        "defaultImgIndex": 1,  # 默认图片索引（取轮播图）
        "activity_signed": 12,  # 已参加人数
        "price": 59,  # 价格
        "activity_unit": "元/人",  # 单位
        "activity_start_date": "2020-07-20",  # 活动开始时间
        "activity_end_date": "2020-08-20",  # 活动结束时间
        "sign_start_date": "2020-07-13",  # 报名开始时间
        "sign_end_date": "2020-07-28",  # 报名结束时间
        "service_tel":"0721-8392580",   # 咨询电话
        "address": "测试",  # 地址
        "activity_content": "虽然做了一件好事，但很有可能因此招来他人的无端猜测，例如被质疑是否藏有其他利己动机等，乃至谴责。即便如此，还是要做好事。",#介绍
        "imageContent":[
            "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1887942828,972848009&fm=26&gp=0.jpg",
            "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1956320807,1368482897&fm=26&gp=0.jpg",
            "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2192842524,640789728&fm=26&gp=0.jpg",
            "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2167237248,612060343&fm=26&gp=0.jpg",
            "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1925142767,3806138753&fm=26&gp=0.jpg",
        ],  # 图片详情
    },

]

initActivityItemData = {
        "activity_id": 0,
        "activity_title": "",  # 标题
        "activity_count": 0,  # 预设参加人数
        "status": 0,  # 状态
        "remark": "",
        "imagesSlider": [
            "请点击插入图片",
            "请点击插入图片",
            "请点击插入图片"
        ],   # 轮播图
        "defaultImgIndex": 0,  # 默认图片索引（取轮播图）
        "activity_signed": 0,  # 已参加人数
        "price": 0,  # 价格
        "activity_unit": "元/人",  # 单位
        "activity_start_date": "2020-07-20",  # 活动开始时间
        "activity_end_date": "2020-08-20",  # 活动结束时间
        "sign_start_date": "2020-07-13",  # 报名开始时间
        "sign_end_date": "2020-07-28",  # 报名结束时间
        "service_tel": "0721-8392580",   # 咨询电话
        "address": "测试",  # 地址
        "activity_content": "虽然做了一件好事，但很有可能因此招来他人的无端猜测，例如被质疑是否藏有其他利己动机等，乃至谴责。即便如此，还是要做好事。",#介绍
        "imageContent": [
            "请点击插入图片",
            "请点击插入图片",
            "请点击插入图片",
            "请点击插入图片",
            "请点击插入图片",
        ],  # 图片详情
    }


class activityItem(shopItem):
    def __init__(self):
        super(activityItem, self).__init__(labelcount=5, displaytype=1)
        self.setFixedSize(500, 300)
        self._setPicSize((300, 300))
        sd = QGraphicsDropShadowEffect()
        sd.setColor(Qt.gray)
        sd.setBlurRadius(8)
        self.setGraphicsEffect(sd)

    def updateData(self, data):
        self._data = data
        # 显示图片
        url = data["imagesSlider"][data["defaultImgIndex"]]
        # ret = self._displayImg(url, self._picLb)
        # if ret is not None:
        #     data["imagesSlider"][data["defaultImgIndex"]] = ret
        self.q_request(url)
        # 显示标题
        font = QFont()
        font.setBold(True)
        font.setPixelSize(14)
        font.setFamily("黑体")
        self._descLbList[0].setFont(font)
        self._descLbList[0].setText(data["activity_title"])

        # 显示价格
        self._descLbList[1].setStyleSheet("color: red")
        font.setPixelSize(20)
        self._descLbList[1].setFont(font)
        self._descLbList[1].setText("¥" + str(data["price"]))

        # 显示活动开始和结束时间
        font.setPixelSize(13)
        font.setBold(False)
        font.setFamily("SimSun")
        font.setItalic(True)
        self._descLbList[2].setFont(font)
        self._descLbList[2].setText("活动开始时间:" + data["activity_start_date"])
        self._descLbList[3].setFont(font)
        self._descLbList[3].setText("活动结束时间:" + data["activity_end_date"])

        # 显示销量和状态
        self._descLbList[4].setFont(font)
        text = "已参加:" + str(data["activity_signed"])
        if not data["status"]:
            text += "   已发布"
        else:
            text += "   已撤销"
        self._descLbList[4].setText(text)


class activityEditWidget(QScrollArea):
    cancelBtnClicked = pyqtSignal()
    goodsStatus = pyqtSignal(bool)
    goodsDelete = pyqtSignal(list)

    def __init__(self, parent=None):
        super(activityEditWidget, self).__init__(parent)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)

        self._mainWidget = QWidget(self)
        # 存储编辑过的信息
        self._data = None

        # 存放正在被编辑的商品
        self._goodsItem = None

        # 当前被按下的轮播图按键
        self._currentSlideBtn = None

        # 判断是否为添加商品初始化界面
        self._isinit = False

        # 轮播图界面
        self._slideShowWidget = QWidget()
        self._slideBtnWidget = QWidget()
        self._slideShowBtn = list()
        for index in range(3):
            self._slideShowBtn.append(slideButton(index))
            if index == 0:
                self._currentSlideBtn = self._slideShowBtn[index]
            self._slideShowBtn[index].currentIndex.connect(self._updateSlidePic)
        self._slideShowLb = picEditableLabel()
        self._slideShowLb.setFixedSize(500, 400)
        self._initslideWdiget()

        # 上传轮播图
        self._slideShowLb.picLbClicked.connect(self._uplaodPic)

        # 信息编辑界面、上下架控制
        self._msgWidget = QWidget()
        self._titleLb = QLabel()
        self._titleLb.setObjectName("msgEditWidgetLb")
        self._titleLineEdit = QLineEdit()
        self._priceLb = QLabel()
        self._priceLb.setObjectName("msgEditWidgetLb")
        self._priceLineEdit = QLineEdit()
        self._activity_unitLb = QLabel()
        self._activity_unitLb.setObjectName("msgEditWidgetLb")
        self._activity_unitLineEdit = QLineEdit()
        self._salesLb = QLabel()
        self._salesLb.setObjectName("msgEditWidgetLb")
        self._stockLb = QLabel()
        self._stockLb.setObjectName("msgEditWidgetLb")
        self._stockLineEdit = QLineEdit()
        self._activityBeginLb = QLabel()
        self._activityBeginLb.setObjectName("msgEditWidgetLb")
        self._activityBeginTimeEdit = QDateTimeEdit()
        self._activityEndLb = QLabel()
        self._activityEndLb.setObjectName("msgEditWidgetLb")

        self._activityEndTimeEdit = QDateTimeEdit()
        self._sign_start_dateLb = QLabel()
        self._sign_start_dateLb.setObjectName("msgEditWidgetLb")
        self._sign_start_dateTimeEdit = QDateTimeEdit()
        self._sign_end_dateLb = QLabel()
        self._sign_end_dateLb.setObjectName("msgEditWidgetLb")
        self._sign_end_dateTimeEdit = QDateTimeEdit()
        self._service_telLb = QLabel()
        self._service_telLb.setObjectName("msgEditWidgetLb")
        self._service_telLineEdit = QLineEdit()
        self._addressLb = QLabel()
        self._addressLb.setObjectName("msgEditWidgetLb")
        self._addressLineEdit = QLineEdit()
        self._activity_contentLb = QLabel()
        self._activity_contentPlainEdit = QPlainTextEdit()

        # 上下架控制
        self._cancelBtn = QPushButton()
        self._submitBtn = QPushButton()
        self._unShelveBtn = QPushButton()
        self._cancelBtn.clicked.connect(self._onCancel)
        self._submitBtn.clicked.connect(self._onSubmit)
        self._unShelveBtn.clicked.connect(self._onUnShelve)
        # self._goodsTypeLb = QLabel()
        # self._goodsTypeLineEdit = QLineEdit()

        # 删除商品
        self._deleteBtn = QPushButton()
        self._deleteBtn.clicked.connect(self._onDelete)

        self._initmsgWidget()

        # 图片详情
        self._detailsWidget = QWidget()
        self._detailsWidget.setMinimumSize(1300, 3000)
        self._detailsPicLb = list()
        for index in range(5):
            self._detailsPicLb.append(picEditableLabel(index))
            self._detailsPicLb[index].picLbClicked.connect(self._uplaodPic)
        glayout = QGridLayout()
        for each in range(self._detailsPicLb.__len__()):
            self._detailsPicLb[each].setMinimumSize(1000, 600)
            glayout.addWidget(self._detailsPicLb[each], each, 0, Qt.AlignCenter)
        glayout.setSpacing(0)
        self._detailsWidget.setLayout(glayout)

        # 图文详情
        font = QFont()
        font.setBold(True)
        font.setFamily("SimSun")
        font.setPixelSize(17)
        self._activity_detialLb = QLabel()
        self._activity_detialLb.setFont(font)
        self._activity_detialLb.setText("图文详情:")
        self._activity_detialLb.setProperty("class", "titleLabel")

        #self._activity_detialLb.setFixedSize(130, 27)
        self._activity_detialLb.setAlignment(Qt.AlignCenter)

        # 整体界面布局
        glayout = QGridLayout()
        glayout.addWidget(self._slideShowWidget, 0, 0, 1, 1, Qt.AlignCenter)
        glayout.addWidget(self._msgWidget, 0, 1, 1, 1, Qt.AlignCenter | Qt.AlignLeft)
        glayout.addWidget(self._activity_contentLb, 1, 0, 1, 2, Qt.AlignCenter)
        glayout.addWidget(self._activity_contentPlainEdit, 2, 0, 2, 2, Qt.AlignCenter)
        glayout.addWidget(self._activity_detialLb, 4, 0, 1, 2, Qt.AlignCenter)
        glayout.addWidget(self._detailsWidget, 5, 0, 1, 2)
        # glayout.setColumnStretch(0, 1)
        # glayout.setColumnStretch(1, 1)
        glayout.setContentsMargins(0, 20, 0, 0)
        self._mainWidget.setLayout(glayout)
        self.setWidget(self._mainWidget)
        self.setMinimumWidth(self.width())

    def _displayimg(self, url, label):
        pix = QPixmap()

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        if url.startswith("http"):
            QApplication.processEvents()
            response = requests.get(url)
            pix.loadFromData(response.content)
            pix = pix.scaled(label.width(), label.height())
            label.setStyleSheet("border:none")
            label.setPixmap(pix)
            image_byte = b64encode(response.content)
            base64_string = image_byte.decode('utf-8')
            QApplication.restoreOverrideCursor()
            return base64_string
        elif url == "请点击插入图片":
            label.setText(url)
            label.setStyleSheet("background-color:gray;border: 1px solid black;")
        else:
            url = url.encode("utf-8")
            image_data = b64decode(url)
            pix.loadFromData(image_data)
            pix = pix.scaled(label.width(), label.height())
            label.setStyleSheet("border:none")
            label.setPixmap(pix)

        QApplication.restoreOverrideCursor()

        return None

    def _initslideWdiget(self):
        vlayout = QVBoxLayout()
        hlayout = QHBoxLayout()

        hlayout.addStretch()
        for index in range(3):
            hlayout.addWidget(self._slideShowBtn[index])
        self._slideBtnWidget.setLayout(hlayout)

        vlayout.addWidget(self._slideShowLb)
        vlayout.addWidget(self._slideBtnWidget)

        self._slideShowWidget.setLayout(vlayout)

    def _initmsgWidget(self):
        # 编辑标题
        font = QFont()
        font.setBold(True)
        font.setFamily("SimSun")
        font.setPixelSize(16)
        self._titleLineEdit.setFont(font)

        # 编辑价格
        self._priceLb.setStyleSheet("color: red")
        font.setPixelSize(23)
        self._priceLb.setFont(font)
        self._priceLb.setText("¥")
        self._priceLb.setAlignment(Qt.AlignRight)
        self._priceLineEdit.setStyleSheet("color: red")
        self._priceLineEdit.setFont(font)
        self._priceLineEdit.setValidator(QDoubleValidator(0, 100000000, 2))

        # 显示销量
        font.setPixelSize(17)
        self._salesLb.setFont(font)

        self._titleLb.setFont(font)
        self._titleLb.setText("标题:")
        self._titleLb.setAlignment(Qt.AlignRight)

        # 已参加人数
        self._stockLb.setFont(font)
        self._stockLb.setText("预设参加人数:")
        self._stockLb.setAlignment(Qt.AlignRight)
        self._stockLineEdit.setValidator(QIntValidator(0, 1000000000))

        # 上下架、取消、删除按键       # gai
        self._cancelBtn.setText("取消")
        self._submitBtn.setText("发布")
        self._unShelveBtn.setText("撤销")
        self._deleteBtn.setText("删除")
        self._cancelBtn.setProperty("class", "editWidgetBtn")
        self._submitBtn.setProperty("class", "editWidgetBtn")
        self._unShelveBtn.setProperty("class", "editWidgetBtn")
        self._deleteBtn.setProperty("class", "editWidgetBtn")

        self._activity_unitLb.setFont(font)
        self._activity_unitLb.setText("单位:")
        self._activity_unitLb.setAlignment(Qt.AlignRight)
        self._activityBeginLb.setFont(font)
        self._activityBeginLb.setText("活动开始时间:")
        self._activityBeginLb.setAlignment(Qt.AlignRight)
        self._activityEndLb.setFont(font)
        self._activityEndLb.setText("活动结束时间:")
        self._activityEndLb.setAlignment(Qt.AlignRight)
        self._sign_start_dateLb.setFont(font)
        self._sign_start_dateLb.setText("活动报名开始时间:")
        self._sign_start_dateLb.setAlignment(Qt.AlignRight)
        self._sign_end_dateLb.setFont(font)
        self._sign_end_dateLb.setText("活动报名结束时间:")
        self._sign_end_dateLb.setAlignment(Qt.AlignRight)
        self._service_telLb.setFont(font)
        self._service_telLb.setText("联系电话:")
        self._service_telLb.setAlignment(Qt.AlignRight)
        self._addressLb.setFont(font)
        self._addressLb.setText("地址:")
        self._addressLb.setAlignment(Qt.AlignRight)
        self._activity_contentLb.setFont(font)
        self._activity_contentLb.setText("活动介绍:")
        # self._activity_contentLb.setStyleSheet("background-color: qlineargradient(x0:0, x1:1, stop: 0 #1fa2ff, "
        #                                       "stop: 0.5 #12d8fa, stop: 1 #a6ffcb);")
        self._activity_contentLb.setObjectName("titleLabel")
        self._activity_contentLb.setProperty("class", "titleLabel")
        #self._activity_contentLb.setFixedSize(130, 27)
        self._activity_contentLb.setAlignment(Qt.AlignCenter)
        self._activity_contentPlainEdit.setMinimumSize(800, 50)
        self._activity_contentPlainEdit.setFont(font)

        self._activityBeginTimeEdit.setDisplayFormat("yyyy-MM-dd")
        self._activityEndTimeEdit.setDisplayFormat("yyyy-MM-dd")
        self._sign_start_dateTimeEdit.setDisplayFormat("yyyy-MM-dd")
        self._sign_end_dateTimeEdit.setDisplayFormat("yyyy-MM-dd")
        self._activityBeginTimeEdit.setCalendarPopup(True)
        self._activityEndTimeEdit.setCalendarPopup(True)
        self._sign_start_dateTimeEdit.setCalendarPopup(True)
        self._sign_end_dateTimeEdit.setCalendarPopup(True)
        self._activityBeginTimeEdit.calendarWidget().setStyleSheet("background-color:#90EE90")
        self._activityEndTimeEdit.calendarWidget().setStyleSheet("background-color:#90EE90")
        self._sign_start_dateTimeEdit.calendarWidget().setStyleSheet("background-color:#90EE90")
        self._sign_end_dateTimeEdit.calendarWidget().setStyleSheet("background-color:#90EE90")

        # 布局
        glayout = QGridLayout()
        glayout.addWidget(self._titleLb, 0, 0, 1, 1, Qt.AlignBottom)
        glayout.addWidget(self._titleLineEdit, 0, 1, 1, 1, Qt.AlignBottom)
        glayout.addWidget(self._submitBtn, 0, 2, 1, 1, Qt.AlignRight | Qt.AlignTop)
        glayout.addWidget(self._priceLb, 1, 0, 1, 1, Qt.AlignBottom)
        glayout.addWidget(self._priceLineEdit, 1, 1, 1, 1, Qt.AlignBottom)
        glayout.addWidget(self._activity_unitLb, 2, 0, 1, 1, Qt.AlignBottom)
        glayout.addWidget(self._activity_unitLineEdit, 2, 1, 1, 1, Qt.AlignBottom)
        glayout.addWidget(self._unShelveBtn, 1, 2, 1, 1, Qt.AlignRight | Qt.AlignTop)
        glayout.addWidget(self._salesLb, 3, 0, 1, 2, Qt.AlignBottom)
        glayout.addWidget(self._deleteBtn, 2, 2, 1, 1, Qt.AlignRight | Qt.AlignTop)
        glayout.addWidget(self._stockLb, 4, 0, 1, 1, Qt.AlignBottom)
        glayout.addWidget(self._stockLineEdit, 4, 1, 1, 1, Qt.AlignBottom)
        glayout.addWidget(self._cancelBtn, 3, 2, 1, 1, Qt.AlignRight | Qt.AlignTop)

        glayout.addWidget(self._activityBeginLb, 5, 0, 1, 1, Qt.AlignBottom)
        glayout.addWidget(self._activityBeginTimeEdit, 5, 1, 1, 1, Qt.AlignBottom)
        glayout.addWidget(self._activityEndLb, 6, 0, 1, 1, Qt.AlignBottom)
        glayout.addWidget(self._activityEndTimeEdit, 6, 1, 1, 1, Qt.AlignBottom)
        glayout.addWidget(self._sign_start_dateLb, 7, 0, 1, 1, Qt.AlignBottom)
        glayout.addWidget(self._sign_start_dateTimeEdit, 7, 1, 1, 1, Qt.AlignBottom)
        glayout.addWidget(self._sign_end_dateLb, 8, 0, 1, 1, Qt.AlignBottom)
        glayout.addWidget(self._sign_end_dateTimeEdit, 8, 1, 1, 1, Qt.AlignBottom)
        glayout.addWidget(self._service_telLb, 9, 0, 1, 1, Qt.AlignBottom)
        glayout.addWidget(self._service_telLineEdit, 9, 1, 1, 1, Qt.AlignBottom)
        glayout.addWidget(self._addressLb, 10, 0, 1, 1, Qt.AlignBottom)
        glayout.addWidget(self._addressLineEdit, 10, 1, 1, 1, Qt.AlignBottom)

        glayout.setSpacing(10)
        glayout.setContentsMargins(0, 0, 0, 0)
        self._msgWidget.setLayout(glayout)

    # 按键切换显示图片
    def _updateSlidePic(self, index):
        self._currentSlideBtn = self.sender()
        ret = self._displayimg(self._data["imagesSlider"][index], self._slideShowLb)
        if ret is not None:
            self._data["imagesSlider"][index] = ret

    # 上传图片时显示图片
    def _updateSlidePicFromFile(self, index):
        ret = self._displayimg(self._data["imagesSlider"][index], self._slideShowLb)
        if ret is not None:
            self._data["imagesSlider"][index] = ret

    def _updateDedetailsPic(self, label):
        ret = self._displayimg(self._data["imageContent"][label.index()], label)
        if ret is not None:
            self._data["imageContent"][label.index()] = ret

    def _onCancel(self):
        self.cancelBtnClicked.emit()

    def _onSubmit(self):
        self.goodsStatus.emit(True)

    def _onUnShelve(self):
        self.goodsStatus.emit(False)

    def _onDelete(self):
        if self._isinit:
            self.goodsDelete.emit([None, ])
        else:
            self.goodsDelete.emit([self._goodsItem, ])

    # 上传轮播图或图片详情图片
    def _uplaodPic(self, mode):
        fd = FileDialog(QFileDialog.AcceptOpen, "选择图片")
        path = fd.getSelectFilePath()
        if path is not None:
            img = cv2.imdecode(np.fromfile(path, dtype=np.uint8), -1)
            # width = img.shape[1]
            # height = img.shape[0]
            # # width_new = 548
            # # height_new = 332
            # width_new = 650
            # height_new = 400
            # # 判断图片的长宽比率
            # if width / height >= width_new / height_new:
            #     img_new = cv2.resize(img, (width_new, int(height * width_new / width)))
            # else:
            #     img_new = cv2.resize(img, (int(width * height_new / height), height_new))

            img_new = img
            #img_new = cv2.resize(img, (900, 900))
            cv2.imwrite('./temp/temp.jpg', img_new)
            with open('./temp/temp.jpg', "rb") as file:
                image_byte = b64encode(file.read())
            base64_string = image_byte.decode('utf-8')
            if mode == -1:
                index = self._currentSlideBtn.index()
                self._data["imagesSlider"][index] = base64_string
                self._updateSlidePicFromFile(index)
            else:
                self._data["imageContent"][mode] = base64_string
                self._updateDedetailsPic(self._detailsPicLb[mode])

    def updateData(self, data, isinit=False):  # gai
        self._data = data
        self._isinit = isinit
        if not isinit:
            self._goodsItem = self.sender()
            self._unShelveBtn.show()
        else:
            self._goodsItem = None
            self._unShelveBtn.hide()

        self._titleLineEdit.setText(data["activity_title"])
        self._priceLineEdit.setText(str(data["price"]))
        self._activity_unitLineEdit.setText(data["activity_unit"])
        self._salesLb.setText("         已参加:" + str(data["activity_signed"]))
        self._stockLineEdit.setText(str(data["activity_count"]))
        self._displayimg(data["imagesSlider"][data["defaultImgIndex"]], self._slideShowLb)
        for each in range(data["imageContent"].__len__()):
            ret = self._displayimg(data["imageContent"][self._detailsPicLb[each].index()], self._detailsPicLb[each])
            if ret is not None:
                data["imageContent"][self._detailsPicLb[each].index()] = ret
        self._activityBeginTimeEdit.setDate(QDate.fromString(data["activity_start_date"], "yyyy-MM-dd"))
        self._activityEndTimeEdit.setDate(QDate.fromString(data["activity_end_date"], "yyyy-MM-dd"))
        self._sign_start_dateTimeEdit.setDate(QDate.fromString(data["sign_start_date"], "yyyy-MM-dd"))
        self._sign_end_dateTimeEdit.setDate(QDate.fromString(data["sign_end_date"], "yyyy-MM-dd"))
        self._service_telLineEdit.setText(data["service_tel"])
        self._addressLineEdit.setText(data["address"])
        self._activity_contentPlainEdit.setPlainText(data["activity_content"])

    # 获取被编辑的数据
    def getEditedData(self):  # gai
        if self._data is not None:
            self._data["activity_title"] = self._titleLineEdit.text()
            self._data["price"] = float(self._priceLineEdit.text())
            self._data["activity_unit"] = self._activity_unitLineEdit.text()
            self._data["activity_count"] = int(self._stockLineEdit.text())
            self._data["activity_start_date"] = self._activityBeginTimeEdit.date().toString("yyyy-MM-dd")
            self._data["activity_end_date"] = self._activityEndTimeEdit.date().toString("yyyy-MM-dd")
            self._data["sign_start_date"] = self._sign_start_dateTimeEdit.date().toString("yyyy-MM-dd")
            self._data["sign_end_date"] = self._sign_end_dateTimeEdit.date().toString("yyyy-MM-dd")
            self._data["service_tel"] = self._service_telLineEdit.text()
            self._data["address"] = self._addressLineEdit.text()
            self._data["activity_content"] = self._activity_contentPlainEdit.toPlainText()

            return self._data

        return None

    # 更新对应的商品信息
    def updateGoodsItem(self):
        if not self._isinit:
            self._goodsItem.updateData(self._data)
            return None
        else:
            ret = activityItem()  # gai
            ret.updateData(self._data)

            return ret

    # 修改上下架信息并返回
    def setSalesStatus(self, status):
        if status:
            self._data["status"] = 0
            return 0
        else:
            self._data["status"] = 1
            return 1

    def currentEditItem(self):
        return self._goodsItem

class activityWidget(QStackedWidget):
    def __init__(self, parent=None):
        super(activityWidget, self).__init__(parent)
        self._handle = activityHandle()

        self._editWidget = activityEditWidget()

        self._data = None
        # 初始化商品列表
        self._goodsScrollArea = QScrollArea()
        self._mainWidget = QWidget()

        self._goodsWidget = QWidget(self._goodsScrollArea)
        self._goodsList = list()
        self._glayout = QGridLayout()
        self._glayout.setSpacing(20)
        self._addGoodsItemBtn = QPushButton()
        self._addGoodsItemBtn.clicked.connect(self._addGoodsItem)
        self._addGoodsItemBtn.setProperty("class", "addBtn")
        # sd = QGraphicsDropShadowEffect()
        # sd.setColor(Qt.gray)
        # sd.setBlurRadius(45)
        # self._addGoodsItemBtn.setGraphicsEffect(sd)
       # self._addGoodsItemBtn.setFixedSize(30, 30)
        self.disPlayGoodsItem([])
        self._goodsScrollArea.setWidget(self._goodsWidget)
        self.setAttribute(Qt.WA_StyledBackground, True)

        self._descLb = QLabel()
        self._descLb.setProperty("class", "pageDescLb")
        self._descLb.setText("活动上架管理")

        self.addWidget(self._mainWidget)
        self.addWidget(self._editWidget)

        # 上下架及页面控制
        self._editWidget.cancelBtnClicked.connect(self._onCancel)
        self._editWidget.goodsStatus.connect(self._onStatusChange)

        # 删除商品
        self._editWidget.goodsDelete.connect(self._onDelete)

        self._mainWidgetLayout = QGridLayout()
        self._mainWidgetLayout.addWidget(self._descLb, 0, 0, 1, 1, Qt.AlignCenter | Qt.AlignTop)
        self._mainWidgetLayout.addWidget(self._goodsScrollArea, 1, 0, 1, 1)
        self._mainWidget.setLayout(self._mainWidgetLayout)

        self.showMaximized()

    def disPlayGoodsItem(self, data, refresh=False, data_refresh=False):
        if refresh:
            for each in range(self._goodsList.__len__()):
                self._glayout.removeWidget(self._goodsList[each])
                self._goodsList[each].deleteLater()
            self._goodsList.clear()
        else:
            self._data = data

        if data_refresh:
            self._data = data

        for each in range(data.__len__()):
            self._goodsList.append(activityItem())
            self._goodsList[each].updateData(data[each])
            self._goodsList[each].shopItemClicked.connect(self._changeWidget)
        for each in range(self._goodsList.__len__()):
            self._glayout.addWidget(self._goodsList[each], each//2+1, each%2, 1, 1, Qt.AlignTop | Qt.AlignLeft)
        self._glayout.addWidget(self._addGoodsItemBtn, 0, 0, 1, 4, Qt.AlignRight | Qt.AlignTop)
        self._goodsWidget.resize(2 * 500 + 150, ((self._goodsList.__len__() - 1) // 2 + 1)
                                 * 315 + 30 + self._addGoodsItemBtn.height())
        self._goodsWidget.setLayout(self._glayout)

    def _reshow(self):
        self._glayout.addWidget(self._addGoodsItemBtn, 0, 0, 1, 4, Qt.AlignRight | Qt.AlignTop)
        for each in range(self._goodsList.__len__()):
            self._glayout.addWidget(self._goodsList[each], each//2+1, each%2, 1, 1, Qt.AlignTop | Qt.AlignLeft)
        self._goodsWidget.resize(2 * 500 + 150, ((self._goodsList.__len__() - 1) // 2 + 1)
                                 * 315 + 30 + self._addGoodsItemBtn.height())

    def _indexOfGoodsItem(self, item):
        for index in range(self._goodsList.__len__()):
            if id(item) == id(self._goodsList[index]):
                return index

        return None

    def _changeWidget(self, data):
        self.sender().setDataIndex(self._data.index(data))
        self.setCurrentIndex(1)
        self._editWidget.updateData(copy.deepcopy(data))

    def _onCancel(self):
        self.setCurrentIndex(0)

    def _new_image_name(self):
        img_name = str(time.time()).replace('.', '') + '.jpg'
        return img_name

    def _get_imgs(self, img_list):
        ret = list()
        for each in img_list:
            if each.startswith("http"):
                try:
                    file = requests.get(each)
                    img = cv2.imdecode(np.fromstring(file.content, np.uint8), 1)
                    imgname = './temp/' + self._new_image_name()
                    ret.append(imgname)
                    cv2.imwrite(imgname, img)
                except Exception as e:
                    print(e)
                    return False, None
            elif each == "请点击插入图片":
                pass
            else:
                url = each.encode("utf-8")
                image_data = b64decode(url)
                img = cv2.imdecode(np.fromstring(image_data, np.uint8), 1)
                imgname = './temp/' + self._new_image_name()
                ret.append(imgname)
                cv2.imwrite(imgname, img)

        return True, ret

    def _get_activity_post_data(self, post_data):
        post_data["create_by"] = "yixianshenji"
        post_data["update_by"] = "yixianshenji"
        post_data["status"] = 0
        post_data["items"] = ""
        state, ret = self._get_imgs(post_data["imagesSlider"])
        state1, ret1 = self._get_imgs(post_data["imageContent"])
        if state and state1 and ret.__len__() > 0 and ret1.__len__() > 0:
            post_data["imagesSlider"] = ret
            post_data["imageContent"] = ret1
            return True, post_data
        else:
            return False, None

    def _onStatusChange(self, status):
        self._editWidget.setSalesStatus(status)
        data = self._editWidget.getEditedData()

        post_data = copy.deepcopy(data)

        if status:
            state, post_data = self._get_activity_post_data(post_data)
            if state:
                state, res = self._handle.updateActivity(post_data)
                if state:
                    data["activity_id"] = res.get("activity_id")
                else:
                    WarningMessageBox("上架失败, 服务器异常").exec()
                    return
            else:
                WarningMessageBox("上架失败, 图片不能为空，或服务器异常").exec()
                return
        else:
            activity_id = post_data["activity_id"]
            state, res = self._handle.activity_sout_out(activity_id)
            if not state:
                WarningMessageBox(" 下架失败, 服务器异常").exec()
                return

        # shutil.rmtree('./temp')
        # os.mkdir('./temp')
        self._editWidget.setSalesStatus(status)
        ret = self._editWidget.updateGoodsItem()
        if ret is not None:
            self._data.append(data)
            ret.shopItemClicked.connect(self._changeWidget)  # gai
            self._goodsList.append(ret)
            self._glayout.addWidget(ret, (self._goodsList.__len__()-1)//2+1, (self._goodsList.__len__()-1)%2,
                                    1, 1, Qt.AlignTop | Qt.AlignLeft)
            self._goodsWidget.resize(2 * 500 + 150, ((self._goodsList.__len__()-1)//2+1)
                                     * (ret.height()+15) + self._addGoodsItemBtn.height()+30)
        else:
            item = self._editWidget.currentEditItem()
            self._data[item.dataIndex()] = data

        self.setCurrentIndex(0)

    def _addGoodsItem(self):
        self.setCurrentIndex(1)
        self._editWidget.updateData(copy.deepcopy(initActivityItemData), True)

    def _onDelete(self, item):
        if item[0] is None:
            self.setCurrentIndex(0)
        else:
            item_data = item[0].getData()
            activity_id = item_data["activity_id"]
            state, res = self._handle.activity_del(activity_id)
            if not state:
                WarningMessageBox("删除失败, 服务器异常").exec()
                return

            self.setCurrentIndex(0)
            # 去除界面布局
            for each in self._goodsList:
                self._glayout.removeWidget(each)
            # 删除对应商品
            index = item[0].dataIndex()
            del self._data[index]
            goodsindex = self._goodsList.index(item[0])
            item[0].setParent(None)
            item[0].deleteLater()
            del self._goodsList[goodsindex]
            #self.disPlayGoodsItem(goodsList)
            # 重新布局
            self._reshow()

def main():
    app = QApplication(sys.argv)

    ui = activityWidget()

   # ui = goodsItem()
    #ui.updateData(json.loads(json.dumps(goodsList))[0])
    ui.show()

    sys.exit(app.exec())

if __name__ == "__main__":
    main()